import { AfterLoad, BeforeInsert, BeforeUpdate, Column, Entity, Index } from 'typeorm'
import bcrypt from 'bcrypt'
import { CommonEntity } from './CommonEntity'
import { EUserStatus } from '@/types/common'

@Entity('users', { engine: 'InnoDB', comment: '用户信息表' })
export default class User extends CommonEntity {
  @Column('varchar', { length: 30, comment: '用户名' })
  @Index('usernameIndex')
  username: string

  password: string

  @Column('varchar', { length: 64, comment: '密码-密文', select: false })
  crypt_pwd?: string

  @Column('varchar', { length: 30, nullable: true, comment: '昵称', default: null })
  nickname?: string

  @Column('char', { length: 11, comment: '手机号', default: '' })
  @Index('phoneIndex')
  phone: string

  @Column('varchar', { length: 100, nullable: true, comment: '头像', default: null })
  avatar?: string

  @Column({ type: 'enum', enum: EUserStatus, comment: '用户状态：1-正常，0-禁用', default: EUserStatus.NORMAL })
  @Index('statusIndex')
  status: EUserStatus

  // 校验明文密码
  async validatePassword(plainPassword: string): Promise<boolean> {
    return await bcrypt.compare(plainPassword, this.crypt_pwd!)
  }

  // 判断当前用户状态是否正常
  isActive(): boolean {
    return this.status === EUserStatus.NORMAL
  }

  // 密码加密
  @BeforeInsert()
  @BeforeUpdate()
  async handlePassword() {
    if (this.password) {
      const salt = await bcrypt.genSalt(+(process.env.BCRYPT_SALT_ROUNDS || 10))
      this.crypt_pwd = await bcrypt.hash(this.password, salt)
    }
  }

  @AfterLoad()
  afterLoad() {
    this.phone = this.phone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') // 手机号脱敏处理
  }
}
